package com.wangzemin.leetcoded.num1311;


import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;

public class Solution {
    public List<String> watchedVideosByFriends(List<List<String>> watchedVideos, int[][] friends, int id, int level) {

        boolean[] visited = new boolean[friends.length];
        Set<Integer> currentLevelFriendIds = Set.of(id);
        for (int i = 0; i < level; level++) {
            Set<Integer> nextLevelFriendIds = new HashSet<>();
            for (Integer currentLevelFriendId : currentLevelFriendIds) {
                for (Integer friend:friends[currentLevelFriendId]) {
                    if (!visited[friend]){
                        nextLevelFriendIds.add(friend);
                        visited[friend] = true;
                    }

                }
            }
            currentLevelFriendIds = nextLevelFriendIds;
        }

        Map<String, Integer> watchTimes = new HashMap<>();
        for (Integer currentLevelFriendId : currentLevelFriendIds) {
            watchedVideos.get(currentLevelFriendId).forEach(watchedVideo ->
                    watchTimes.put(watchedVideo, watchTimes.getOrDefault(watchedVideo,0)+1));
        }
        return watchTimes.entrySet().stream().sorted((a,b)->{
            if (!a.getValue().equals(b.getValue())){
                return Integer.compare(a.getValue(),b.getValue());
            }
            return a.getKey().compareTo(b.getKey());
        }).map(Entry::getKey).collect(Collectors.toList());

    }
}